﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace MM.Common.Base
{
    public sealed class DataCrypto
    {
        // Fields
        private RijndaelManaged CryptoService = new RijndaelManaged();

        // Methods
        public string Decrypting(string Source, string Key)
        {
            byte[] buffer = Convert.FromBase64String(Source);
            MemoryStream stream = new MemoryStream(buffer, 0, buffer.Length);
            this.CryptoService.Key = this.GetLegalKey(Key);
            this.CryptoService.IV = this.GetLegalIV(Key);
            ICryptoTransform transform = this.CryptoService.CreateDecryptor();
            CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Read);
            StreamReader reader = new StreamReader(stream2);
            string str = "\r\n\t";
            try
            {
                str = reader.ReadToEnd();
            }
            catch (Exception exception)
            {
                string message = exception.Message;
            }
            return str;
        }

        public string Encrypting(string Source, string Key)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(Source);
            MemoryStream stream = new MemoryStream();
            this.CryptoService.Key = this.GetLegalKey(Key);
            this.CryptoService.IV = this.GetLegalIV(Key);
            ICryptoTransform transform = this.CryptoService.CreateEncryptor();
            CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);
            stream2.Write(bytes, 0, bytes.Length);
            stream2.FlushFinalBlock();
            return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length);
        }

        private byte[] GetLegalIV(string Key)
        {
            string s = Key;
            this.CryptoService.GenerateIV();
            int length = this.CryptoService.IV.Length;
            if (s.Length > length)
            {
                s = s.Substring(0, length);
            }
            else if (s.Length < length)
            {
                s = s.PadRight(length, ' ');
            }
            return Encoding.ASCII.GetBytes(s);
        }

        private byte[] GetLegalKey(string Key)
        {
            string s = Key;
            this.CryptoService.GenerateKey();
            int length = this.CryptoService.Key.Length;
            if (s.Length > length)
            {
                s = s.Substring(0, length);
            }
            else if (s.Length < length)
            {
                s = s.PadRight(length, ' ');
            }
            return Encoding.ASCII.GetBytes(s);
        }
    }
}
